<?php
require_once("Dimension1.php");
require_once("Dimension2.php");
class Dimension1Manager {
    private $_db;
    
    public function __construct($db) {
        $this->setDb($db);
    }
    
    public function add(Dimension1 $d1) {
        $q = $this->_db->prepare('INSERT INTO Dimension1 VALUES (:refD1,:nom)');
        $q->bindValue(':nom', $d1->getNom());
        $q->bindValue(':refD1', $d1->getRefD1());
        $q->execute(); 
    }
    
    public function count() {
        return $this->_db->query('SELECT COUNT(*) FROM Dimension1')->fetchColumn();
    }
    
    public function delete(Dimension1 $d1) {
        $exec = $this->_db->exec("DELETE FROM Dimension1 WHERE refD1 = '".$d1->getRefD1()."'");
        return $exec;
        
    }
    
    public function get($refD1) {
        $q = $this->_db->query("SELECT refD1, nom FROM Dimension1 WHERE refD1 = '".$refD1."'");
        $donnees = $q->fetch(PDO::FETCH_ASSOC);      
        return new Dimension1($donnees);
    }
    
    public function getList() {
        $persos = array();
            
        $q = $this->_db->prepare('SELECT refD1, nom FROM Dimension1');
        $q->execute();
            
        while ($donnees = $q->fetch(PDO::FETCH_ASSOC))
        {
            $persos[] = new Dimension1($donnees);
        }
            
        return $persos;
    }
    
    /**
     * Retourne les Dimension2 associées à 1 Dimension1
     * @param type $refD1
     * @return type 
     */
    public function getDimension2($refD1) {
        $q = $this->_db->prepare("SELECT refD2, d2.refD1, titre, descr FROM Dimension2 d2, Dimension1 d1 where d2.refD1 = d1.refD1 and d2.refD1 = :refD1");
        $q->bindValue(':refD1', $refD1);
        
        $q->execute();
        $d1 = $this->get($refD1);

        while($lignes=$q->fetch(PDO::FETCH_OBJ)) {           
            $d2 = new Dimension2($d1, $lignes->refD2, $lignes->titre, $lignes->descr);
            $d1->addDimension2($d2);
        }
        return $d1->getLesDimensions2();
    }
    
    public function setDb(PDO $db) {
        $this->_db = $db;
    }
    
}
?>